package com.yunc.modules.sys.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysMessage;
import com.yunc.modules.sys.entity.vo.SysMessageSearchVO;
import com.yunc.modules.sys.mapper.SysMessageMapper;
import com.yunc.modules.sys.service.ISysMessageService;
import com.yunc.modules.sys.service.ISysMessageUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 消息
 *
 * @author congcong tao
 * @create 2020/1/14 14:04
 */
@Service("sysMessageService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage> implements ISysMessageService {

    private final SysMessageMapper sysMessageMapper;
    private final ISysMessageUserService sysMessageUserService;

    @Override
    public List<SysMessage> pageInfo(Page<SysMessage> page, SysMessageSearchVO sysMessage) {
        return sysMessageMapper.pageInfo(page, sysMessage);
    }

    @Override
    public int getDayCount() {
        // 当天的时间
        Date date = new Date();
        DateTime beginDateTime = DateUtil.beginOfDay(date);
        DateTime endDateTime = DateUtil.endOfDay(date);
        return sysMessageMapper.getDayCount(beginDateTime, endDateTime);
    }

    @Override
    public int getDayCountUser(String userId) {
        // 当天的时间
        Date date = new Date();
        DateTime beginDateTime = DateUtil.beginOfDay(date);
        DateTime endDateTime = DateUtil.endOfDay(date);
        return sysMessageMapper.getDayCountUser(beginDateTime, endDateTime, userId);
    }

    @Override
    public int getCountUser(String userId, String status) {
        return sysMessageMapper.getCountUser(userId, status);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R saveMessage(SysMessage message) {
        message.setCreateTime(new Date());
        boolean flag = this.save(message);
        if (!flag) {
            return R.error();
        }
        // 发布到消息
        String userIds = message.getUserIds();
        // 开多线程
        sysMessageUserService.insertList(message.getType(), message.getTitle(), message.getId(), userIds);
        return R.ok();
    }
}
